﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace SharpMap.Presentation.Wpf.StyleView
{
    class StyleItemEditorTemplateSelector : DataTemplateSelector
    {
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            StyleViewEntry entry = item as StyleViewEntry;
            FrameworkElement listItem = container as FrameworkElement;
            DataTemplate template = null;
            if (entry != null && listItem != null && entry.Value != null)
            {
                Type type = entry.Value.GetType();
                template = FindExactTypeTemplate(type, listItem);

                while (template == null && ((type = type.BaseType) != null))
                {

                    template = FindExactTypeTemplate(type, listItem);
                }
            }
            if (template == null)
            {
                template = FindExactTypeTemplate("DefaultValueTemplate", listItem);
            }
            return template as DataTemplate;
        }

        private static DataTemplate FindExactTypeTemplate(Type entryType, FrameworkElement listItem)
        {
            
            ComponentResourceKey dataTemplateKey =
                new ComponentResourceKey(typeof(LayerStyleView), entryType);
            return listItem.TryFindResource(dataTemplateKey) as DataTemplate;
        }

        private static DataTemplate FindExactTypeTemplate(string name, FrameworkElement listItem)
        {

            ComponentResourceKey dataTemplateKey =
                new ComponentResourceKey(typeof(LayerStyleView), name);
            return listItem.TryFindResource(dataTemplateKey) as DataTemplate;
        }
    }
}
